package com.leonzhangxf.ioc.web;

import com.leonzhangxf.ioc.BeanFactory;
import com.leonzhangxf.ioc.Injector;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import java.io.IOException;

import static com.leonzhangxf.ioc.web.WebContextAttributes.APP_CLASS_KEY;
import static com.leonzhangxf.ioc.web.WebContextAttributes.BEAN_FACTORY_KEY;
import static com.leonzhangxf.ioc.web.WebContextAttributes.INJECTOR_KEY;

/**
 * @author leonzhangxf
 */
public class BeanFactoryContextLoadListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();

        String appClassName = servletContext.getInitParameter(APP_CLASS_KEY);

        Class<?> appClass = null;
        try {
            appClass = Injector.class.getClassLoader().loadClass(appClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            Injector injector = Injector.builder().build(appClass);
            servletContext.setAttribute(INJECTOR_KEY, injector);

            BeanFactory beanFactory = injector.provideBeanFactory();
            servletContext.setAttribute(BEAN_FACTORY_KEY, beanFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();

        servletContext.setAttribute(INJECTOR_KEY, null);
        servletContext.setAttribute(BEAN_FACTORY_KEY, null);
    }
}
